#include "../include/SearchEngineServer.h"
#include "../include/ProtocolParser.h"
#include <iostream>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

// 静态成员初始化
SearchEngineServer *SearchEngineServer::_instance = nullptr;

SearchEngineServer *SearchEngineServer::getInstance()
{
    if (_instance == nullptr)
    {
        _instance = new SearchEngineServer();
    }
    return _instance;
}

SearchEngineServer::SearchEngineServer()
    : _server_port(8888), _thread_pool_size(4)
{
    std::cout << "创建搜索引擎服务器..." << std::endl;
    init();
}

void SearchEngineServer::init()
{
    // 加载配置
    loadConfiguration();

    // 创建线程池
    _threadpool = std::make_unique<ThreadPool>(_thread_pool_size);
    std::cout << "创建线程池，大小: " << _thread_pool_size << std::endl;

    // 创建TCP服务器
    _tcpserver = std::make_unique<TcpServer>(_server_port, _threadpool.get());
    std::cout << "创建TCP服务器，端口: " << _server_port << std::endl;

    // 设置回调函数
    _tcpserver->setConnectionCallback(
        std::bind(&SearchEngineServer::onConnection, this, std::placeholders::_1));
    _tcpserver->setMessageCallback(
        std::bind(&SearchEngineServer::onMessage, this, std::placeholders::_1, std::placeholders::_2));
    _tcpserver->setCloseCallback(
        std::bind(&SearchEngineServer::onClose, this, std::placeholders::_1));

    std::cout << "✅ 搜索引擎服务器初始化完成" << std::endl;
}

void SearchEngineServer::loadConfiguration()
{
    // 直接使用单例
    Configuration *config = Configuration::getInstance();

    // 确保调用 load 方法
    std::cout << "🔧 开始加载配置文件..." << std::endl;
    config->load("server.conf");
    std::cout << "🔧 配置文件加载调用完成" << std::endl;

    _server_port = config->getInt("server.port", 8888);
    _thread_pool_size = config->getInt("server.thread_pool_size", 4);

    std::cout << "加载配置 - 端口: " << _server_port
              << ", 线程数: " << _thread_pool_size << std::endl;
}

void SearchEngineServer::start()
{
    std::cout << "🚀 启动搜索引擎服务器..." << std::endl;
    std::cout << "==========================================" << std::endl;
    std::cout << "架构: Reactor + ThreadPool" << std::endl;
    std::cout << "协议: TLV (Tag-Length-Value)" << std::endl;
    std::cout << "端口: " << _server_port << std::endl;
    std::cout << "线程池: " << _thread_pool_size << " 个线程" << std::endl;
    std::cout << "功能: 1-关键字推荐, 2-网页搜索" << std::endl;
    std::cout << "==========================================" << std::endl;

    try
    {
        _tcpserver->start();
    }
    catch (const std::exception &e)
    {
        std::cerr << "💥 服务器启动失败: " << e.what() << std::endl;
        throw;
    }
}

void SearchEngineServer::stop()
{
    std::cout << "🛑 停止搜索引擎服务器..." << std::endl;
    if (_tcpserver)
    {
        _tcpserver->stop();
    }
    if (_threadpool)
    {
        _threadpool->stop();
    }
    std::cout << "✅ 服务器已停止" << std::endl;
}

// IO线程 - 处理网络事件
void SearchEngineServer::onConnection(TcpConnectionPtr conn)
{
    std::cout << "🔗 新的客户端连接: fd=" << conn->getFd() << std::endl;

    // !!! 注释掉自动发送欢迎消息的代码 !!!
    // Message welcome_msg;
    // welcome_msg.tag = 0;
    // welcome_msg.value = "欢迎连接到搜索引擎服务器！";
    // welcome_msg.length = welcome_msg.value.size();
    // conn->send(welcome_msg.serialize());
    // std::cout << "✅ 欢迎消息发送完成" << std::endl;

    // 只记录连接，不发送任何数据
    std::cout << "✅ 客户端连接已建立，等待请求..." << std::endl;

    // 不要调用 conn->close() !
}

void SearchEngineServer::onMessage(TcpConnectionPtr conn, const std::string &msg)
{
    std::cout << "📨 收到客户端数据: " << msg.size() << " 字节" << std::endl;

    // 提交给计算线程池处理
    _threadpool->enqueue([this, conn, msg]()
                         {
        std::string processed_msg = msg; // 拷贝数据
        this->doTaskThread(conn, processed_msg); });
}

void SearchEngineServer::onClose(TcpConnectionPtr conn)
{
    std::cout << "❌ 客户端断开连接: fd=" << conn->getFd() << std::endl;
}

// 计算线程 - 处理业务逻辑
void SearchEngineServer::doTaskThread(TcpConnectionPtr conn, std::string &msg)
{
    try
    {
        std::cout << "🎯 计算线程处理请求..." << std::endl;

        // 处理粘包半包 - 从数据流中提取完整的TLV包
        std::vector<std::string> packets = ProtocolParser::splitPackets(msg);

        if (packets.empty())
        {
            std::cout << "❌ 没有完整的TLV包" << std::endl;
            return;
        }

        // 处理每个完整的TLV包
        for (const auto &packet : packets)
        {
            // 解析TLV协议
            Message request = ProtocolParser::parse(packet);

            if (request.length > 0)
            {
                std::cout << "🎯 解析TLV消息 - Tag: " << request.tag
                          << ", Length: " << request.length
                          << ", Value: '" << request.value << "'" << std::endl;

                switch (request.tag)
                {
                case 1: // 关键字推荐
                    ProtocolParser::handleKeywordRecommendation(conn, request.value);
                    break;
                case 2: // 网页搜索
                    ProtocolParser::handleWebSearch(conn, request.value);
                    break;
                default:
                    std::cout << "❌ 未知消息类型: " << request.tag << std::endl;

                    // 发送错误响应
                    Message error_response;
                    error_response.tag = 0;
                    error_response.value = "{\"error\":\"未知消息类型\"}";
                    error_response.length = error_response.value.size();
                    conn->send(error_response.serialize());
                    break;
                }
            }
            else
            {
                std::cout << "❌ 消息解析失败" << std::endl;
            }
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << "💥 处理请求异常: " << e.what() << std::endl;

        // 发送错误响应
        Message error_response;
        error_response.tag = 0;
        error_response.value = "{\"error\":\"服务器内部错误: " + std::string(e.what()) + "\"}";
        error_response.length = error_response.value.size();

        conn->send(error_response.serialize());
    }
}